<template>
	<cusNavVue :title="userName"></cusNavVue>
	<view class="page-content">
		<view class="message-list">
			<view :class="['message-item', item.from === meid ? 'right': 'left']" v-for="item in messageList" :key="item.id">
				<image class="user-avator" v-if="item.from!== meid" :src="userInfo.avator" mode=""></image>
				<view v-if="typeof(item.message) === 'string'">
					<rich-text :nodes="item.message"></rich-text>
				</view>
				<view v-else-if="item.message.type==='audio'" class="">
					<up-icon name="mic" @click="playAudio(item.message)"></up-icon>
					<!-- <text >音频播放</text> -->
				</view>
				<view v-else-if="item.message.type==='video'" class="">
					<!-- <up-icon name="mic" @click="playAudio(item.message)"></up-icon> -->
					<video src=""></video>
					<!-- <text >音频播放</text> -->
				</view>
				<image class="user-avator" v-if="item.from=== meid" :src="myInfo.avator" alt="" ></image>
			</view>
		</view>
		<view class="bottom-message-model">
			<view class="send-model">
				<up-icon name="volume" @longpress="handleRecorder" @touchend="stopRecorder"></up-icon>
				<up-input class="message-input" placeholder="请输入内容" border="surround" v-model="messageValue" @change="change">
					<template #suffix>
						<up-button type="success" size="mini" @click="doSend">发送</up-button>
					</template>
				</up-input>
				<up-icon name="more-circle" @click="handleIconImage"></up-icon>
				<up-icon name="plus-circle" @click="changeFile"></up-icon>
			</view>
			<view :class="['icon-image-list', showIcon ? 'show' : 'hide']">
				<image @click="selectedIcon(item)" v-for="item in iconImageList" :key="item.code" class="icon-image" :src="item.url" mode=""></image>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import {onLoad} from '@dcloudio/uni-app';
import io from '@hyoga/uni-socket.io';
import cusNavVue from '../../components/cus-nav/cus-nav.vue';

// 表情地址的响应式数组
const iconImageList = ref([
	{url: '/static/logo.png', code: 'logo'},
	{url: '/static/icon/bs.png', code: 'bs'},
	{url: '/static/icon/eye.png', code: 'eye'},
	{url: '/static/icon/mg.png', code: 'mgui'},
	{url: '/static/icon/sq.png', code: 'sq'},
])
const imgUrlList = ref([])
// alogoa  => logo 替换成<img src="/static/logo.png" class="icon-image">
const messageValue = ref('')
const showIcon = ref(false)
const handleIconImage = () => {
	showIcon.value = !showIcon.value
}
const innerAudioContext = uni.createInnerAudioContext();
const playAudio = (audioInfo) => {
	console.log(audioInfo)
	// 设置音频播放地址
	innerAudioContext.src = audioInfo.url
	//如果是正在播放的状态那么暂停，如果不是，那么开始播放
	if(innerAudioContext.paused) {
		innerAudioContext.play()
	} else {
		// console.log(innerAudioContext.paused)
		innerAudioContext.pause()
	}
}
const selectedIcon = (iconItem) => {
	messageValue.value += iconItem.code
}
let socket = null
let times = ref(0); //统计重连的次数
let timer = null
// 定义一个方法，在这个方法里面链接咱们得websocket服务
const recorderManager = uni.getRecorderManager()
// 重置定时器心跳检测
const setPing = () => {
	timer && clearInterval(timer)
	timer = setInterval(() => {
		socket.emit('ping')
	}, 5000)
}
const changeFile = () => {
	uni.chooseImage({
		success(res) {
			console.log(res)
			// 调用接口，上传图片
			setTimeout(() => {
				// 拿到图片上传之后的地址
				const url = 'https://zsyx-image.baidu.com/0/pic/197968965_762413223_1723451076.jpg'
				imgUrlList.value = [{
					url
				}]
				imgUrlList.value.forEach(item => {
					console.log(item)
					messageValue.value += `<img src="${item.url}" class="message-image" />`
				})
			}, 2000)
		}
	})
}
const handleRecorder = () => {
	recorderManager.start()
}
const stopRecorder = () => {
	recorderManager.stop()
}
const doConnect = () => {
	// 创建websocket链接
	socket = io('ws://localhost:3000', {
		path: '/socket',
		reconnection: false,
	  query: {
		  meid: meid.value
	  },
	  transports: [ 'websocket', 'polling' ],
	  timeout: 5000,
	});
	socket.on('connect', () => {
		times.value = 0
		console.log('链接服务端连接成功')
		setPing()
		// 连接成功之后注册一个接受消息的事件
		socket.on('recive', (res) => {
			setPing()
			console.log('客户端接收到了服务端发送过来的消息', res)
			// 接受到客户端返回过来的消息之后，我要把每一个表情对应的code转换为实际的表情进行展示
			messageList.value.push(res)
		})
		socket.on('pang',() => {
			console.log('pang事件触发了')
		})
	})
	// connect_error是连接错误
	socket.on('connect_error', () => {
		console.log('websocket报错了')
		timer && clearInterval(timer)
		if(times.value>=5) {
			uni.showToast({
				title:'已经重新连接5次了，但是重新连接失败了，请检查网络'
			})
			times.value = 0
			return
		}
		doConnect()
		times.value += 1
	})
	// disconnect是断开连接的事件
	socket.on('disconnect', () => {
		// console.log('链接断开了')
		// 链接断开了，咱们可以去手动重新连接一下
		// doConnect()
		uni.showToast({
			title:'链接断开了，正在自动重连~'
		})
		timer && clearInterval(timer)
		times.value += 1
		doConnect()
	})
}
// 表情code转换成图片标签字符串
const strToImgStr = (str) => {
	let newStr = str
	iconImageList.value.map(item => {
		console.log(str.includes(item.code))
		console.log('------');
		console.log(newStr);
		//code不是src里面的内容也不能是
		if(newStr.includes(item.code) && !newStr.includes('/'+item.code)) {
			// replaceAll不能修改原字符串
			// 举例：newStr = 'a' ,使用newStr.reaplaceAll('a', 'b')方法把'a'改成了'b'，newStr还是'a'
			//newStr.reaplaceAll('a', 'b')返回的结果是b
			newStr = newStr.replaceAll(item.code, `<img src="${item.url}" class="icon-image">`)
		}
	})
	console.log(newStr)
	return newStr
}
const personList = [
		{
			userName: '张学友',
			avator: 'https://img0.baidu.com/it/u=781435481,24052815&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1729789200&t=1d6e0402531cbb654a4910645d519904',
			userid: 'zxy'
		},
		{
			userName: '刘德华',
			avator: 'https://img2.baidu.com/it/u=1001860741,127553111&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1729789200&t=655ef53507699175cbfe56fdec93396f',
			userid: 'ldh'
		},
		{
			userName: '郭富城',
			avator: 'https://img2.baidu.com/it/u=627100025,1003920823&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1729789200&t=a7b3e5bcde1d7cf27e5cadcca4168dcc',
			userid: 'gfc'
		},
		{
			userName: '李少斌',
			avator: 'https://img2.baidu.com/it/u=627100025,1003920823&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1729789200&t=a7b3e5bcde1d7cf27e5cadcca4168dcc',
			userid: 'bin'
		}
	]
const meid = ref('') // 发送人的id
const toId = ref('') // 接收人的id

const userName = ref('')

// 当前登录人的个人信息
const myInfo = ref({})
const userInfo = ref({})
//模拟调用接口获取对方的用户信息以及我的用户信息
const getUserInfo =() => {
	setTimeout(() => {
		myInfo.value = personList.find(item => item.userid === meid.value) || {}
		userInfo.value = personList.find(item => item.userid === toId.value) || {}
	},1000)
}


const videoUrl = ref('')
onLoad((options) => {
	// 参数里面 userid，useName代表者代表着我要跟谁聊天
	// 再构造一个参数meid代表我是谁，我想要站在我的角度跟A聊天，也想在这个项目里面站在A与我聊天
	console.log(options)
	toId.value = options.userid
	meid.value = options.meid
	userName.value = options.username
	getUserInfo()
	doConnect()
	
	recorderManager.onStop(function (res) {
		// 停止录音之后，要把这个录音上传拿到一个上传成功之后的url地址，发送的时候生成一个能播放录音的标签
		videoUrl.value = 'https://web-ext-storage.dcloud.net.cn/uni-app/ForElise.mp3'
		console.log(videoUrl.value)
		const messageInfo = {
			from: meid.value,
			to: toId.value,
			message: {
				type: 'audio',
				url: videoUrl.value
			}
		}
		messageList.value.push(messageInfo)
		socket.emit('send',messageInfo)
	})
})

const chatUser = ref()
const messageList  = ref([{
	id: 1,
	from: 'zxy',
	message: ' 您好，您发布的房子，我想具体咨询一下',
	to: 'bin'
},{
	id: 2,
	from: 'bin',
	message: '哪个小区的房子',
	to: 'zxy'
}])
const doSend = () => {
	const messageInfo = {
		id: Date.now(),
		message: strToImgStr(messageValue.value),
		from: meid.value,
		to: toId.value
	}
	console.log(strToImgStr(messageValue.value)),
	console.log(messageInfo)
	setPing()
	// 点击发送，把构造的消息对象放到消息列表中
	messageList.value.push(messageInfo)
	// 在这里发送消息，也就是触发服务端注册一个事件
	socket.emit('send',messageInfo)
	messageValue.value = ''
}

</script>

<style lang="scss" scoped>
	.bottom-message-model{
		width: 100vw;
		position: fixed;
		bottom: 30rpx;
	}
	.send-model {
		width: 100vw;
		display: flex;
		align-items: center;
		padding: 0 20rpx;
		box-sizing: border-box;
		
		.message-input {
			flex: 1;
		}
	}
	.user-avator{
		width: 100rpx;
		height: 100rpx;
	}
	.message-item{
		display: flex;
		align-items: center;
		&.right{
			justify-content: flex-end;
		}
		.icon-image{
			width: 40rpx;
			height: 40rpx;
			margin-right: 6rpx;
		}
		.message-image{
			width: 100rpx;
			height: auto;
		}
	}
	.icon-image-list {
		display: flex;
		transition: all .5s;
		&.show {
			height: auto;
			opacity: 1;
			padding: 15rpx;
			.icon-image{
				width: 40rpx;
				height: 40rpx;
				margin-right: 10rpx;
			}
		}
		&.hide {
			opacity: 0;
			height: 0rpx;
			.icon-image{
				width: 0rpx;
				height: 0rpx;
			}
		}
	}
</style>